use anyhow::Result;

use crate::{
    app_mu_stor::{self, OStor},
    mod_auth::liclient,
};
use serde::{Deserialize, Serialize};
use std::time::Duration;

#[derive(Serialize, Deserialize)]
struct LicRequest {
    head: String,
    content: String,
}

#[derive(Serialize, Deserialize, Debug)]
enum AuthControl {
    AuthSave(String),
    Unknow(),
}

pub async fn _verify_await() -> Result<()> {
    let stor_hand = app_mu_stor::OStor::new().await?;
    loop {
        if let Ok(Some(license)) = stor_hand.clone().get_auth(None, "app_lic").await {
            let app_liclient = liclient::LiClient::new();
            if app_liclient.verify_license(license) {
                break;
            }
        }
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
    Ok(())
}

pub async fn genlic_await(content: String) -> Result<bool> {
    let mut result = false;
    let app_liclient = liclient::LiClient::new();
    let stor_hand = app_mu_stor::OStor::new().await?;
    if let Some(lic_str) = app_liclient.gen_license(&content) {
        if let Ok(()) = stor_hand.clone().set_auth(None, "app_lic", lic_str).await {
            result = true;
        };
    }
    Ok(result)
}

#[tauri::command]
pub async fn gen_actoken_cmd() -> String {
    let app_liclient = liclient::LiClient::new();
    let actoken = app_liclient.gen_actoken();
    actoken
}

#[tauri::command]
pub async fn active_license_cmd(content: String) -> bool {
    let mut result = false;
    if let Ok(res) = genlic_await(content).await {
        result = res;
    }
    println!("active_license_cmd result:{}", result);
    result
}

#[tauri::command]
pub async fn verify_lic_cmd() -> bool {
    let mut result = false;
    if let Ok(stor_hand) = OStor::new().await {
        if let Ok(Some(license)) = stor_hand.clone().get_auth(None, "app_lic").await {
            let app_liclient = liclient::LiClient::new();
            result = app_liclient.verify_license(license);
        }
    }
    println!("verify_lic_cmd result:{}", result);
    return result;
}
